package com.xcity.game.achievement.helper;

import com.xcity.game.achievement.Achievement;
import com.xcity.game.achievement.Achievement.State;
import com.xcity.game.achievement.AchievementHelper;
import com.xcity.game.achievement.AchievementTemplate;

/**
 * 成就类型：使用物品<br/>
 * 2个参数：①物品id(-1表示任何物品) ②完成该成就需使用的总次数
 * @author yang.li
 *
 */
public class UseItemHelper implements AchievementHelper {

	@Override
	public boolean update(Achievement refer, int... vals) {
		if (refer.getState() == State.REWARDED) {
			return false;
		}
		int id = obtainItemId(vals);
		int count = obtainItemCount(vals);
		// 累计总数
		int newCount = refer.getValue().getIntValue(DEFAULT_VAL_KEY) + count;
		refer.getValue().put(DEFAULT_VAL_KEY, newCount);
		
		// 累计对应物品数量
		if (id == obtainItemId(refer.getTemplate())) {
			String key = String.valueOf(id);
			newCount = refer.getValue().getIntValue(key) + count;
			refer.getValue().put(key, newCount);
		}
		return isFinished(refer);
	}

	@Override
	public boolean isFinished(Achievement refer) {
		if (refer.getState() == State.INITED) {
			int id = obtainItemId(refer.getTemplate());
			int count = obtainItemCount(refer.getTemplate());
			String key = id != 0 ? String.valueOf(id) : DEFAULT_VAL_KEY;
			if (refer.getValue().getIntValue(key) >= count) {
				refer.setState(State.FINISHED);
				return true;
			}
		}
		return false;
	}
	
	static int obtainItemId(int... vals) {
		return vals != null && vals.length > 0 ? vals[0] : 0;
	}
	
	static int obtainItemId(AchievementTemplate template) {
		return (int) template.getCondition(0);
	}
	
	static int obtainItemCount(int... vals) {
		return vals != null && vals.length > 1 ? vals[1] : 0;
	}
	
	static int obtainItemCount(AchievementTemplate template) {
		return (int) template.getCondition(1);
	}

}
